package com.vavr.checkincms.service.impl;

import java.util.Optional;
import cn.hutool.core.util.StrUtil;
import com.vavr.checkincms.common.constant.CommonConstants;
import com.vavr.checkincms.common.domain.ResultEnum;
import com.vavr.checkincms.convert.SystemUserInfoConvert;
import com.vavr.checkincms.domain.bo.SystemUserInfoBO;
import com.vavr.checkincms.domain.data.SystemUserInfoDO;
import com.vavr.checkincms.mapper.SystemLoginMapper;
import com.vavr.checkincms.service.SystemUserService;
import com.vavr.checkincms.util.CheckinRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * SystemUserServiceImpl
 *
 * @since 2024.12
 */
@Slf4j
@Service
public class SystemUserServiceImpl implements SystemUserService {
    /**
     * 签到时间相关配置
     */
    private final SystemLoginMapper systemLoginMapper;

    public SystemUserServiceImpl(SystemLoginMapper systemLoginMapper) {
        this.systemLoginMapper = systemLoginMapper;
    }

    @Override
    public String addUser(SystemUserInfoBO bo) {
        // 权限判断
        Optional<SystemUserInfoDO> systemUserInfoOptional = CheckinRequestUtils.getUserFromRequestAttributes()
                .map(v -> systemLoginMapper.selectById(v.getOperatorId()));
        if (systemUserInfoOptional.isEmpty() || !StrUtil.equals(systemUserInfoOptional.get().getOperatorLevel(),
                CommonConstants.IS_ADMIN)) {
            return ResultEnum.UNAUTHORIZED_REQUEST.getMsg();
        }
        // 首先确认必传参数是否齐全
        if (bo == null || !StrUtil.isAllNotBlank(bo.getOperatorAccount(), bo.getOperatorCode(), bo.getOperatorName(),
                bo.getTel())) {
            return ResultEnum.MISS_PARAM.getMsg();
        }
        // 然后根据手机号或者账号确认是否存在相同账号信息
        if (systemLoginMapper.queryUserInfoByTel(bo.getTel()) != null
                || systemLoginMapper.queryUserInfoByAccount(bo.getTel()) != null) {
            return ResultEnum.USER_ALREADY_EXISTS.getMsg();
        }
        // 新增用户
        return systemLoginMapper.insert(SystemUserInfoConvert.INSTANCE.boToDo(bo)) > 0
                ? ResultEnum.ADD_USER_SUCCESS.getMsg()
                : ResultEnum.ADD_USER_ERROR.getMsg();
    }

    @Override
    public String updateUser(SystemUserInfoBO bo) {
        Optional<SystemUserInfoDO> systemUserInfoOptional = CheckinRequestUtils.getUserFromRequestAttributes()
                .map(v -> systemLoginMapper.selectById(v.getOperatorId()));
        if (systemUserInfoOptional.isEmpty() || !StrUtil.equals(systemUserInfoOptional.get().getOperatorLevel(),
                CommonConstants.IS_ADMIN)) {
            return ResultEnum.UNAUTHORIZED_REQUEST.getMsg();
        }
        return systemLoginMapper.updateById(SystemUserInfoConvert.INSTANCE.boToDo(bo)) > 0
                ? ResultEnum.ADD_USER_SUCCESS.getMsg()
                : ResultEnum.ADD_USER_ERROR.getMsg();
    }
}
